from asyncio import exceptions
from tokenize import TokenError

import jwt
from django.http import JsonResponse
from rest_framework import status
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken

from apps.app01 import models
from lenovo import settings


class RefreshTokenView(APIView):
    """刷新access token的API视图"""

    authentication_classes = []

    def post(self, request, *args, **kwargs):
        refresh_token = request.data.get('refresh_token')

        if not refresh_token:
            return JsonResponse({'error': '需要提供刷新令牌'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            refresh = RefreshToken(refresh_token)
            new_access_token = str(refresh.access_token)  # 获取新的 access token

            # 如果需要同时更新 refresh token，可以这样做：
            # new_refresh_token = str(refresh)

            response_data = {
                'access_token': new_access_token,
                # 如果需要发送新的 refresh token，取消注释下面一行：
                # 'refresh': new_refresh_token,
            }

            return JsonResponse(response_data, status=status.HTTP_200_OK)

        except TokenError as e:
            return JsonResponse({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

